<?php
	$root = "http://".$_SERVER['HTTP_HOST']."/".substr($_SERVER['PHP_SELF'], 1, strpos(substr($_SERVER['PHP_SELF'], 1), "/"))."/";
?>
<!DOCTYPE html>
<!-- 
文件用途:KJ趋势分析
作者:hjl
制作日期:2012-12-20
最后编辑人:hjl
最后编辑时间:2012-12-20
-->
<html lang="en">
  <head>
    <title>KJ趋势分析</title>
    <base href="<?php echo $root;?>">
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0"> 
    <?php include '../pages/common/importBaseCss.php'; ?>
    <!-- bootstrap-modal -->
	<script type="text/javascript">
	var aclData= {available:"true",print:"true"}
	var breadCrumbDatas = [{"id":1,href:"index.jsp",clazz:'icon-home'},
			{id:2,text:'数据库管理系统',href:'pages/dataManagementSystem/index.jsp'},
			{id:3,text:'KJ趋势分析'}
		   ];
	var dynamicFormDatas = {
		   mineDatas:[{value:1,display:"矿井1"},
			{value:2,display:"矿井2"},
			{value:3,display:"矿井3"},
			{value:4,display:"矿井4"}
		   ],
		   sensorCategoryDatas:[{value:1,display:"瓦斯"},
			{value:2,display:"温度"},
			{value:3,display:"负压"},
			{value:4,display:"风速"},
			{value:5,display:"CO"},
			{value:6,display:"环境其他"}
		   ]
	};		      
	</script>
    </head>
    <body>
		<div id="loading_layer" style="display:none"><img src="img/ajax_loader.gif" alt="" /></div>
		<!-- style switcher -->
		<div class="style_switcher">
		</div>
		
		<div id="maincontainer" class="clearfix">
			<!-- header -->
            <header>
                <div class="navbar navbar-fixed-top">
                    <div class="navbar-inner">
                    </div>
                </div>
            </header>
            <!-- main content -->
            <div id="contentwrapper">
                <div class="main_content">
                    <!-- breadCrumb -->
                    <nav>
                        <div id="jCrumbs" class="breadCrumb module">
                        </div>
                    </nav>
                    <div class="row-fluid">
						<h3 class="heading">KJ趋势分析</h3>
						<div class="row-fluid">	
							<div class="span12">
								<div class="well sepH_no">
									<form id="searchForm" class="form-inline sepH_no">
  										<label class="checkbox" for="search_mineNo">矿井:
  											<select class="input-small" name="mineNo" id="search_mineNo"></select>
										</label>
  										<label class="checkbox" for="search_type">类别:
  											<select class="input-small" name="sensorCategory" id="search_sensorCategory"></select>
										</label>
  										<label class="checkbox" for="search_position">位置:
  											<select class="input-small" name="position" id="search_position" 
  												data-bind="options:positionDatas,positionsCaption: '请选择',
                                				optionsText: 'display',optionsValue: 'value'",>
  											</select>
										</label>							
  										<label for="search_startDate">开始-日期:
  											<div class="input-append date" id="dp_start">
												<input class="input-small" type="text" readonly="readonly" name="startDate" id="search_startDate"/><span class="add-on"><i class="splashy-calendar_day_up"></i></span>
											</div>
  										</label>
  										<label for="search_endDate">结束-日期:
  											<div class="input-append date" id="dp_end">
												<input class="input-small" type="text" readonly="readonly" name="endDate" id="search_endDate"/><span class="add-on"><i class="splashy-calendar_day_down"></i></span>
											</div>
  										</label>
										<input type="hidden" name="rangeDate" id="search_rangeDate"/> 
  										<input type="submit" class="btn btn-gebo" value="生成图表"></input>
									</form>
								</div>
							</div>								
						</div>
						<div class="row-fluid">
							<div class="span12">
								<div id="chartWell" class="well" style="display:none;">
									<div id="chartContainer" style="width:100%;height:400px"></div>
								</div>
							</div>
						</div>
					</div>
					
					<!-- hide elements -->
					<div class="hide">
					   
					</div>
					
                </div>
            </div>
            
			<!-- sidebar -->
            <a href="javascript:void(0)" class="sidebar_switch on_switch ttip_r" title="隐藏侧边栏">侧边栏</a>
            <div class="sidebar" id="sidebar">
			</div>
		</div>
		<?php include '../pages/common/importBaseJs.php'; ?>
		<script src="lib/Highcharts/js/highcharts.js"></script>
		<script src="lib/Highcharts/js/modules/exporting.js"></script>
		<!-- app.js 
		<script src="js/app/example/listbox.js"></script>
		-->
<script type="text/javascript">
	/*
	*文件用途:kj趋势分析
	*作者:hjl
	*制作日期:2012-12-11
	*最后编辑人:hjl
	*最后编辑时间:2012-12-11
	*/	
	//================
	//模块入口
	//================
    $(document).ready(function() {
    	if("undefined" != typeof aclData){
        	if("undefined" != typeof dynamicFormDatas){
				app.buildDynamicForm(dynamicFormDatas);
			}
			app.regSubmit();
			app.actions();
		}else{
			smoke.alert('对不起,权限信息丢失',{ok:"关闭"},function(e){
				window.location.href = "index.jsp";
			});
		}
    });
    app = {
		//================
		//创建表单中动态项
		//================       	
      	buildDynamicForm: function(data){
      		var mineDatas = data.mineDatas;
      		var sensorCategoryDatas = data.sensorCategoryDatas;
      		if(mineDatas!=null){
      			amplify.publish("buildSelectOption",$("#search_mineNo"),mineDatas);
      		}
      		if(sensorCategoryDatas!=null){
      			amplify.publish("buildSelectOption",$("#search_sensorCategory"),sensorCategoryDatas);
      		}
      	},
		//================
		//其他操作
		//================       	
      	actions : function(){
      		//位置选择栏联动菜单
      		$("#search_mineNo").change(
      			function(){
      				if($("#search_sensorCategory option:selected").val()!=""
      				&&$("#search_mineNo option:selected").val()!=""){
      					var data = {};
      					data.mineNo = $("#search_mineNo option:selected").val();
      					data.sensorCategory = $("#search_sensorCategory option:selected").val();
      					app.getPositionDatas(data);
      				}
      			}
      		);
      		$("#search_sensorCategory").change(
      			function(){
      				if($("#search_sensorCategory option:selected").val()!=""
      				&&$("#search_mineNo option:selected").val()!=""){
      					var data = {};
      					data.mineNo = $("#search_mineNo option:selected").val();
      					data.sensorCategory = $("#search_sensorCategory option:selected").val();
      					app.getPositionDatas(data);      				
      				}      			
      			}
      		);
      		//时间选择
      		$('#dp_start').datepicker({language:'zh-CN',format: "yyyy-mm-dd"}).on('changeDate', function(ev){
				var dateText = $(this).data('date');
				var endDateTextBox = $('#dp_end input');
				if (endDateTextBox.val() != '') {
				var testStartDate = new Date(dateText);
				var testEndDate = new Date(endDateTextBox.val());
				if (testStartDate > testEndDate) {
						endDateTextBox.val(dateText);
					}
				}
				else {
					endDateTextBox.val(dateText);
				};
				var addDay =  moment(dateText).add('days',5).format("YYYY-MM-DD");
				$('#dp_end').datepicker('setEndDate', addDay);
				$('#dp_end').datepicker('setStartDate', dateText);
				$('#dp_start').datepicker('hide');
				$('#dp_start input').qtip('destroy');
				$('#dp_end input').qtip('destroy');				
			});
			$('#dp_end').datepicker({language:'zh-CN',format: "yyyy-mm-dd"}).on('changeDate', function(ev){
				var dateText = $(this).data('date');
				var startDateTextBox = $('#dp_start input');
				if (startDateTextBox.val() != '') {
					var testStartDate = new Date(startDateTextBox.val());
					var testEndDate = new Date(dateText);
					if (testStartDate > testEndDate) {
						startDateTextBox.val(dateText);
					}
				}	
				else {
					startDateTextBox.val(dateText);
				};
				var subDay = moment(dateText).subtract('days',5).format("YYYY-MM-DD");
				$('#dp_start').datepicker('setStartDate', subDay);
				$('#dp_start').datepicker('setEndDate', dateText);
				$('#dp_end').datepicker('hide');
				$('#dp_start input').qtip('destroy');
				$('#dp_end input').qtip('destroy');
			});	
      	},
		//================
		//得到位置数据
		//================      	
      	getPositionDatas : function(data){
      		$("<option value=''>正在加载中</option>").appendTo($("#search_position"));
      		$.getJSON("json/chart/getPositionDatas.json",data,function(msg){
				var dataModel = {};
				dataModel.positionDatas = msg;				
				var viewModel = ko.mapping.fromJS(ko.toJS(dataModel));
				ko.applyBindings(viewModel);
			});
      	},
      	regSubmit : function(){
      		var postForm = $("#searchForm");
			var ttip_validator = postForm.validate({
				onkeyup: false,
				errorClass: 'error',
				validClass: 'valid',
				highlight: function(element) {
					//$(element).closest('div').addClass("f_error");
				},
				unhighlight: function(element) {
					//$(element).closest('div').removeClass("f_error");
				},
                rules: {
					mineNo: { required: true},
					sensorCategory: { required: true},
					position: { required: true},
					startDate: { required: true},
					endDate: { required: true }
				},
				invalidHandler: function(form, validator) {
					$.sticky("表单中存在错误,请更正后提交!", {autoclose : 5000, position: "top-right", type: "st-error" });
				},
				errorPlacement: function(error, element) {
					// Set positioning based on the elements position in the form
					var elem = $(element);
					// Check we have a valid error message
					if(!error.is(':empty')) {
						if( (elem.is(':checkbox')) || (elem.is(':radio')) ) {
							// Apply the tooltip only if it isn't valid
							elem.filter(':not(.valid)').parent('label').parent('div').find('.error_placement').qtip({
								overwrite: false,
								content: error,
								position: {
									my: 'left bottom',
									at: 'center right',
									viewport: $(window),
									adjust: {
										x: 6
									}
								},
								show: {
									event: false,
									ready: true
								},
								hide: false,
								style: {
									classes: 'ui-tooltip-red ui-tooltip-rounded' // Make it red... the classic error colour!
								}
							})
							// If we have a tooltip on this element already, just update its content
							.qtip('option', 'content.text', error);
						} else {
							// Apply the tooltip only if it isn't valid
							elem.filter(':not(.valid)').qtip({
								overwrite: false,
								content: error,
								position: {
									my: 'bottom left',
									at: 'top right',
									viewport: $(window),
                                    adjust: { x: -8, y: 6 }
								},
								show: {
									event: false,
									ready: true
								},
								hide: false,
								style: {
									classes: 'ui-tooltip-red ui-tooltip-rounded' // Make it red... the classic error colour!
								}
							})
							// If we have a tooltip on this element already, just update its content
							.qtip('option', 'content.text', error);
						};
                        
					}
					// If the error is empty, remove the qTip
					else {
						if( (elem.is(':checkbox')) || (elem.is(':radio')) ) {
							elem.parent('label').parent('div').find('.error_placement').qtip('destroy');
						} else {
							elem.qtip('destroy');
						}
					}
				},
				submitHandler : function(form){
					app.submit(postForm);
				},				
				success: $.noop // Odd workaround for errorPlacement not firing!
			});
			
			//elem.qtip('destroy');      	
      	},
		//================
		//提交生成图表的数据
		//================       	
      	submit : function(form){
			var postData = form.formSerialize();
			$("#chartWell").show();
			$("#chartWell #chartContainer").html("正在加载中...");
        	$.ajax({
                    type : "post",
                    url : "json/chart/chart.json",
                    data : postData,
                    dataType : "json",
                    beforeSend : function(XMLHttpRequest){
                        form.find("#chartBtn").addClass("disabled").removeClass("btn-gebo").val("处理中...");
                    },
                    success : function(msg,textStatus){
						form.find("#chartBtn").removeClass("disabled").addClass("btn-gebo").val("生成图表");
						var data = {};
						data.msg = msg;
						data.mineDisplay = $("#search_mineNo option:selected").text();
      					data.sensorCategoryDisplay = $("#search_sensorCategory option:selected").text();
						data.positionDisyplay = $("#search_position option:selected").text();
						data.startDateVal = $("#search_startDate").val();
						data.endDateVal = $("#search_endDate").val();
						app.chart(data);
                    },
                    error : function(XMLHttpRequest, textStatus, errorThrown){
                    	form.find("#chartBtn").removeClass("disabled").addClass("btn-gebo").val("生成图表");
                    	smoke.alert('服务器出错,请稍候再试',{ok:"取消"});
                    }
         	}); 			      	
      	},
      	chart : function(data){
			var option = {
            	chart: {
                	renderTo: 'chartContainer',
                	type: 'line',
               		marginRight: 130,
                	marginBottom: 40
            	},
            	title: {
                	text: data.mineDisplay+"-"+data.sensorCategoryDisplay+"-"+data.positionDisyplay,
                	x: -20
            	},
            	subtitle: {
                	text: data.startDateVal+"-"+data.endDateVal,
                	x: -20
            	},
            	plotOptions: {
                	line: {
                    	dataLabels: {
                        	enabled: true
                    	}
                	}
            	},
            	xAxis: {
                	title: {
                    	text: '时间'
                	},
                	type: 'datetime',
                	dateTimeLabelFormats: {
						second: '%H:%M:%S',
    					minute: '%e. %b %H:%M',
    					hour: '%b/%e %H:%M',
    					day: '%e日/%b',
    					week: '%e. %b',
    					month: '%b %y',
    					year: '%Y'
                	},
                	tickInterval : 24 * 3600 * 1000 * 1//一天画一个x刻度
            	},
            	yAxis: {
                	title: {
                    	text: '值(单位)'
                	},
                	plotLines: [{
                    	value: 0,
                    	width: 1,
                    	color: '#808080'
                	}]
            	},
            	tooltip: {
                	formatter: function() {
                    	return '<b>'+ this.series.name +'</b><br/>'+
                        '时间:'+moment(this.x).format("YYYY-MM-DD HH:mm") +' 值:'+ this.y;
                	}
            	},
            	legend: {
                	layout: 'vertical',
                	align: 'right',
                	verticalAlign: 'top',
                	x: -10,
                	y: 100,
                	borderWidth: 0
            	},
            	series: [{
                	name: data.sensorCategoryDisplay
            	}]
        	};
            var chartDatas = [];    	
        	var msg = data.msg;
        	jQuery.each(msg, function(i) {
          		chartDatas.push([moment(msg[i].dateTime).valueOf(),msg[i].value]);
          	});
          	option.series[0].data = chartDatas;
          	var chart = new Highcharts.Chart(option);
      	
      	}
	};
</script>
		<script src="js/gebo_common.js"></script>
	</body>
</html>